package com.greyshark.sanotrive.main

import android.content.Intent
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.*
import com.common.app.data.bean.KeyEvents.EVENT_TYPE_MESSAGE_RELAY_DATA
import com.common.app.data.bean.KeyEvents.KEY_MAIN_SWITCH_TAB
import com.common.app.dialog.EmulatorCheckDialog
import com.common.app.helper.*
import com.common.app.utls.*
import com.common.app.utls.Constants.ScanQrCodeReqCode.Companion.SCAN_LOGIN_CODE
import com.common.app.utls.Constants.curMainTabPosition
import com.common.base.app.extras.*
import com.common.base.utils.*
import com.common.base.utils.ActivityCollector.finishAllNotIndex
import com.common.base.widget.btm_nav_view.*
import com.google.zxing.client.android.Intents
import com.jeremyliao.liveeventbus.LiveEventBus
import com.common.app.utls.ApkDownLoadUtils
import com.greyshark.sanotrive.R
import com.greyshark.sanotrive.databinding.ActivityMainBinding
import com.module.ble.listener.CusBleDeviceInfoExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.listener.CusSdkSettingExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AizoSDKUtil.getBindRingInfo
import com.module.ble.utils.AizoSDKUtil.initAizoServiceSdk
import com.module.ble.utils.AizoSDKUtil.onDestroyRingSdk
import com.module.ble.utils.BluetoothPairingUtil
import me.yokeyword.fragmentation.ISupportFragment
import java.util.*

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：APP主界面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_MAIN_ACTIVITY)
class MainActivity : AppActivity<ActivityMainBinding, MainViewModel>(), BtmNavViewListener,
    CusSdkSettingExpandListener, CusConnectBleDeviceExpandListener, CusBleDeviceInfoExpandListener {

    override fun getViewModel() = MainViewModel::class.java
    override fun getViewContentBinding() = ActivityMainBinding.inflate(layoutInflater)
    override fun isShowLoading(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true
    override fun isShowToolBar(): Boolean = false
    override fun getPlaceholderView() = mViewContentBinding.mPlaceholder
    override fun isShowError(): Boolean = false

    private val mFragments = TreeMap<Int, ISupportFragment>()
    private val items = TreeMap<Int, BtmNavItemView>()

    private var loginOut: Boolean = false

    private var apkDownLoadUtils: ApkDownLoadUtils? = null

    private var checkUpRun: Boolean = false//检查更新是否进行中
    private var checkUpLastRun: Boolean = false//第一次不执行
    private var uid: String = ""

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var commonMessageRelayModel: CommonMessageRelayModel? = null
    private var runFirstTransit = false//是否已执行首次中转

    override fun onResume() {
        super.onResume()

        AppUtils.isNeedUpdateApp(this).yes {
            updateApp()
        }
    }

    override fun initViews() {
        super.initViews()
        SpUtilsManagement.putInt(KeyPre.KEY_DOWN_CLOUD_DATA_PROGRESS, 1)

        initAizoServiceSdk(AizoSDKUtil.getRingFirm())

        loadFragments()
        val fragments = ArrayList<ISupportFragment>()
        var firstKey = AppConfigHelper.getHomeMenuDefaultIndex()
        var has = false
        mFragments.forEach {
            (firstKey == it.key).yes { has = true }
            fragments.add(it.value)
        }
        has.no { firstKey = 0 }
        //菜单数量只有一个或没有隐藏菜单列表
        (fragments.size <= 1).yes { mViewContentBinding.bottomBar.gone() }
        fragments.isEmpty().yes {
            mViewContentBinding.bottomBar.gone()
            showEmpty("当前没有配置菜单")
            return
        }
        mViewContentBinding.bottomBar.create(items, firstKey)
        mViewContentBinding.bottomBar.setBtmNavViewListener(this)
        loadMultipleRootFragment(
            R.id.mainContainer,
            mViewContentBinding.bottomBar.getIdIndex(),
            *fragments.toTypedArray()
        )
        showContent()
        this.localClassName
        curMainTabPosition = 0

        uid = UserHelper.getUid()

//        RingCusServiceController.bindToLifecycle(this, setOf(
//            RingCusServiceController.ServiceType.SPORT,
//        ))
    }

    override fun lazyInitData() {
        super.lazyInitData()

        getUserInfo()

//        changeConfigUI()

        toMessageRelayAc()

        AizoSDKUtil.setDeviceDataSyncTime(30, this)


        val currentTime = TimeUtils.getTimeDateLong()
        val currentUtcOffset = TimeUtils.getCurrentUtcOffset()

        Log.e(TAG, "YQ: lazyInitData-------currentTime： ${currentTime} -------currentUtcOffset：${currentUtcOffset}")

        // 将云端数据的时间戳转换为当前设备时区
        val localTimestamp = TimeUtils.convertTimestampWithUtcOffset(
            timestamp = 1749625144602,
            utcOffset = currentUtcOffset,
            targetUtcOffset = -5
        )
        val ustLocalTimestamp = TimeUtils.convertTimestampWithUtcOffset(
            timestamp = 1749625144602,
            utcOffset = currentUtcOffset,
            targetUtcOffset = -5
        )
        Log.e(TAG, "YQ: lazyInitData-------localTimestamp： ${localTimestamp}----UST:${ustLocalTimestamp}")
    }

    override fun initEvents() {
        super.initEvents()

        AizoSDKUtil.addBleDeviceInfoExpandListener(this)
        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        LiveEventBus.get(KeyEvents.KEY_REQUEST_USER_INFO_DATA).observe(this) {
            getUserInfo()
        }

        LiveEventBus.get(KeyEvents.EVENT_TOKEN_EXPIRED, String::class.java)
            .observe(this) {
//                loginOut.no {
//                    loginOut = true
//                    UserHelper.logout()
//                    showAlertDialogOneBtn(
//                        getString(R.string.common_i_know_tip2),
//                        getString(R.string.common_prompt_zh2),
//                        getString(R.string.token_invalidate) + it,
//                        true
//                    )
//                }
            }

        //打开扫描二维码
        LiveEventBus.get(KeyEvents.KEY_OPEN_SCAN_QR_CODE).observe(this) {
            QRCodeHelper.startZxing(this, SCAN_LOGIN_CODE)
        }

        //主页切换至首模块
        LiveEventBus.get(KEY_MAIN_SWITCH_TAB, Int::class.java).observe(this) {
            finishAllNotIndex()
            mViewContentBinding.bottomBar.select(if (it in 0 until items.size) it else 0)
        }

        //app检查升级
        LiveEventBus.get(KeyEvents.MSG_TYPE_CHECK_APP_VER).observe(this) {
            AppUtils.isNeedUpdateApp(this).yes {
                updateApp()
            }
        }

        //中转数据
        LiveEventBus.get(
            EVENT_TYPE_MESSAGE_RELAY_DATA,
            String::class.java
        ).observe(this) {
//            jumpByLinkUrl(it, "首页deeplink")
        }


//        //刷新默认
//        LiveEventBus.get(KeyEvents.EVENT_TYPE_REFRESH_CONFIG_UI).observe(this) {
//            changeConfigUI()
//        }


        LiveEventBus.get(KeyEvents.KEY_AICHAT_STOP_AI_MSG).observe(this){
            requestStopAiMsg()
        }

    }

    override fun onDestroy() {
        // 在适当的时候停止监听（如Activity销毁时）
        BluetoothPairingUtil.stopBluetoothStateListener()
        onDestroyRingSdk(true)
        super.onDestroy()
    }

    //加载主界面所有页面
    private fun loadFragments() {
        AppConfigHelper.apply {
            loadHome()
            loadFind()
            loadStrategy()
            loadMe()
        }
    }

    //更新用户信息
    private fun getUserInfo() {
        //未登录
        if (!UserHelper.isLogin()) {
            return
        }

        mViewModel.getUserInfo().observe(this) {
            it.isSuccess().yes {
                UserHelper.updateUser(UserHelper.getUser(), it.Data)
                getUserGoalInfo()
            }
        }
    }

    private fun getUserGoalInfo() {
        //未登录
        if (!UserHelper.isLogin()) return
        mViewModel.getUserGoalInfo().observe(this) {
            it.isSuccess().yes {
                it.Data?.let { userGoalBeanIt->
                    SpUtilsManagement.putParcelable(KeyPre.KEY_GOAL_USER_BEAN, userGoalBeanIt)
                }
            }
        }
    }

    //自动更新
    private fun updateApp() {
//        if (!checkUpLastRun) {
//            checkUpLastRun = true
//            return
//        }
//        if (checkUpRun) return
//        checkUpRun = true
//        mViewModel.requestVersion {
//            checkUpRun = false
//        }.observe(this) {
//            checkUpRun = false
//            it.isSuccess().yes {
//                it.Data?.let { it1 ->
//                    //强制改为强更
//                    it1.forced = 2//强制强更
//
//                    (getOnlyDigits(
//                        VersionUtils.getVerName(this),
//                        false
//                    ) >= getOnlyDigits(it1.versionName?:"0", false)).no {
//                        if (apkDownLoadUtils == null) {
//                            apkDownLoadUtils = ApkDownLoadUtils(this, it.Data)
//                        }
//                        apkDownLoadUtils?.showDialog(supportFragmentManager)
//                    }
//                }
//
//            }
//        }
    }

    //戒指设备绑定
    private fun upBindRingInfo(){
        if (SpUtilsManagement.getBoolean(KeyPre.KEY_HAS_REPORT_DEVICE)) return
        getBindRingInfo()?.let { ringInfoIt->
            mViewModel.upBindRing(1,ringInfoIt.serialNumber,ringInfoIt.ringName,ringInfoIt.ringMac,0,0).observe(this) {
                it.isSuccess().yes {
                    it.Data?.let {dataIt->
                        AizoSDKUtil.curRingInfoBean?.let {curRingInfoBeanIt->
                            curRingInfoBeanIt.id = dataIt.id
                            curRingInfoBeanIt.color = dataIt.color
                            curRingInfoBeanIt.size = dataIt.size
                            curRingInfoBeanIt.upTime = TimeUtils.getTimeDateLong()
                        }
                        AizoSDKUtil.updateRingInfo()
                    }
                    SpUtilsManagement.putBoolean(KeyPre.KEY_HAS_REPORT_DEVICE,true)
                }
            }
        }
    }

    override fun onBtmNavViewClick(id: Int, oldId: Int) {
        showHideFragment(mFragments[id], null)
        curMainTabPosition = id
//        when (curMainTabPosition) {
//            1 -> {
//                mViewContentBinding.bottomBar.setBackgroundColor(getColor(R.color.black))
//            }
//            else -> {
//                mViewContentBinding.bottomBar.setBackgroundColor(getColor(R.color.white))
//            }
//        }
    }

    override fun onBtmNavViewSameClick(id: Int) {
        if (id == FRAGMENT_ID_HOME) LiveEventBus.get(
            KeyEvents.EVENT_MAIN_MENU_REFRESH,
            Int::class.java
        ).post(id)
        if (id == FRAGMENT_ID_FITNESS) LiveEventBus.get(KeyEvents.EVENT_GAME_MENU_REFRESH).post(id)
    }

    private fun loadHome() {
        val live = RouterHelper.obtainARouterFragment(RouterHub.ROUTER_HOME_FRAGMENT)
        if (live != null) {
            mFragments[FRAGMENT_ID_HOME] = live
            items[FRAGMENT_ID_HOME] = LottieNavItemView(
                this,
                FRAGMENT_ID_HOME,
                getString(R.string.app_menu_home),
//                "bottom_home.json"
                null,
                unSelectedIconId = R.mipmap.index_bottom_bar_hy_un_select,
                selectedIconId = R.mipmap.index_bottom_bar_hy_select
            )
        }
    }

    private fun loadFind() {
        val live = RouterHelper.obtainARouterFragment(RouterHub.ROUTER_CIRCLE_FRAGMENT)
        if (live != null) {
            mFragments[FRAGMENT_ID_SLEEP] = live
            items[FRAGMENT_ID_SLEEP] = LottieNavItemView(
                this,
                FRAGMENT_ID_SLEEP,
                getString(R.string.app_menu_circle),
                null,
                unSelectedIconId = R.mipmap.index_bottom_bar_qz_un_select,
                selectedIconId = R.mipmap.index_bottom_bar_qz_select
            )
        }
    }

    private fun loadStrategy() {
        val live = RouterHelper.obtainARouterFragment(RouterHub.ROUTER_OVERVIEW_FRAGMENT)
        if (live != null) {
            mFragments[FRAGMENT_ID_FITNESS] = live
            items[FRAGMENT_ID_FITNESS] = LottieNavItemView(
                this,
                FRAGMENT_ID_FITNESS,
                getString(R.string.app_menu_overview),
                null,
                unSelectedIconId = R.mipmap.index_bottom_bar_gl_un_select,
                selectedIconId = R.mipmap.index_bottom_bar_gl_select
            )
        }
    }

    private fun loadMe() {
        val me = RouterHelper.obtainARouterFragment(RouterHub.ROUTER_ME_FRAGMENT)
        if (me != null) {
            mFragments[FRAGMENT_ID_ME] = me
            items[FRAGMENT_ID_ME] = LottieNavItemView(
                this,
                FRAGMENT_ID_ME,
                getString(R.string.app_menu_me),
                null,
                unSelectedIconId = R.mipmap.index_bottom_bar_me_un_select,
                selectedIconId = R.mipmap.index_bottom_bar_me_select
            )
        }
    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (System.currentTimeMillis() - exitTime > 2000) {
//                showToast("再按一次退出程序")
//                exitTime = System.currentTimeMillis()
//            } else {
//                val home = Intent(Intent.ACTION_MAIN)
//                home.addCategory(Intent.CATEGORY_HOME)
//                startActivity(home)
//            }
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SCAN_LOGIN_CODE) {
            //扫描登录二维码处理结果
            val text: String = data?.getStringExtra(Intents.Scan.RESULT) ?: return
            LogUtils.e(TAG, "内容：$text")
        }
    }

    override fun onOneButtonOKClick() {
        super.onOneButtonOKClick()

//        UserHelper.logout()
//        LaunchHelper.launchLogin()
//        ActivityCollector.finishAllNotLogin()

        postDelay(200) {
            LiveEventBus.get("key_logout_app").post(true)
            restart()
        }
    }


    private fun changeConfigUI() {
        AppConfigHelper.getSacrificeShow().yes {
            //"公祭日"灰白模式
            GrayManagerUtils.instance?.setLayerGrayType(mViewBinding.root)
        }
    }

    private fun requestUpMsgState(contentId: List<String>?) {
    }

    private fun toMessageRelayAc() { //执行中转业务

        if (commonMessageRelayModel == null) return
        if (runFirstTransit) return

        runFirstTransit = true

        commonMessageRelayModel?.skipPath.isNullOrEmpty().no {

            if ("null" == commonMessageRelayModel?.skipPath) return


            commonMessageRelayModel?.skipPath?.contains("Fragment")?.yes {
//                LiveEventBus.get(KeyEvents.MSG_TYPE_CHANGE_MAIN_TAB_TO_GAME).postDelay(this,300)
                when(commonMessageRelayModel?.skipPath){
                    RouterHub.ROUTER_HOME_FRAGMENT-> LiveEventBus.get(RouterHub.ROUTER_HOME_FRAGMENT).post(this)
                    RouterHub.ROUTER_CIRCLE_FRAGMENT-> LiveEventBus.get(RouterHub.ROUTER_CIRCLE_FRAGMENT).post(this)
                    RouterHub.ROUTER_ME_FRAGMENT-> LiveEventBus.get(RouterHub.ROUTER_ME_FRAGMENT).post(this)
                }
                return
            }

            showToast("正在跳转页面,请稍等~")

            LiveEventBus.get(EVENT_TYPE_MESSAGE_RELAY_DATA, CommonMessageRelayModel::class.java).postDelay(commonMessageRelayModel,300)
        }


    }

    private fun requestStopAiMsg() {
        mViewModel.requestStopAiMsg {
        }.observe(this) {
        }
    }


    override fun onCurrentActivityGoals(data: String?) {
    }

    override fun onDeviceDataSyncTime(state: Boolean) {
        showToast("设置同步时间成功！")
    }

    override fun onConnect(macStr: String?) {
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
    }

    override fun onDisconnect(macStr: String?) {
    }

    override fun onHandleDevice(type: Int, state: Boolean) {
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
//        if (result && isDebugModel()) showToast("设备绑定成功！")
    }

    override fun onDevicePowerState(electricity: String, workingMode: Int) {
    }

    override fun onGetDeviceInfo() {
        upBindRingInfo()
    }

}